# encrypt_client.py - 支持轨迹数据加密
import requests
import json
import time
from typing import Dict, Any, Optional, List


class TrailEncryptor:
    def __init__(self, server_url: str = "http://localhost:3000"):
        self.server_url = server_url

    def encrypt_trail_data(
        self, trail_data: Dict[str, Any]
    ) -> Optional[Dict[str, Any]]:
        """
        加密完整的轨迹数据

        Args:
            trail_data: 完整的轨迹数据字典

        Returns:
            加密结果字典或None（如果失败）
        """
        url = f"{self.server_url}/encrypt-trail"

        try:
            response = requests.post(url, json=trail_data, timeout=30)
            result = response.json()

            if result.get("success"):
                return {
                    "original_size": result["originalDataSize"],
                    "encrypted": result["encrypted"],
                    "encrypted_size": len(result["encrypted"]),
                    "compression_ratio": len(result["encrypted"])
                    / result["originalDataSize"],
                    "timestamp": result["timestamp"],
                }
            else:
                print(f"加密失败: {result.get('error', '未知错误')}")
                return None

        except requests.exceptions.RequestException as e:
            print(f"请求失败: {e}")
            return None
        except json.JSONDecodeError as e:
            print(f"响应解析失败: {e}")
            return None

    def encrypt_coordinates(self, x: float, y: float) -> Optional[Dict[str, Any]]:
        """
        加密单个坐标（保持向后兼容）
        """
        url = f"{self.server_url}/encrypt"
        data = {"x": x, "y": y}

        try:
            response = requests.post(url, json=data, timeout=10)
            result = response.json()

            if result.get("success"):
                return {
                    "original": result["input"],
                    "encrypted": result["encrypted"],
                    "timestamp": int(time.time() * 1000),
                }
            else:
                print(f"坐标加密失败: {result.get('error', '未知错误')}")
                return None

        except Exception as e:
            print(f"坐标加密请求失败: {e}")
            return None


def create_sample_trail_data():
    """创建示例轨迹数据"""
    return {
        "trail": [
            {"x": 110, "y": 6, "t": 1755228768034, "s": 1.281, "tm": 86, "isd": 0},
            {"x": 155, "y": 24, "t": 1755228768041, "s": 6.9238, "tm": 7, "isd": 0},
            {"x": 218, "y": 52, "t": 1755228768049, "s": 8.6178, "tm": 8, "isd": 0},
            {"x": 421, "y": 547, "t": 1755228770817, "s": 0.0017, "tm": 577, "isd": 0},
        ],
        "click": [{"x": 421, "y": 547, "t": 1755229520643}],
        "hover": [{"el": "div.verify-move-block", "dur": 15, "t": 1755228769033}],
        "slider": [],
        "startTime": 1755228767948,
        "endTime": 1755231032352,
        "browser": {"name": "Edge", "version": "139.0.0.0"},
        "os": {"name": "Windows", "version": "10"},
        "screen": {
            "resolution": {"width": 1920, "height": 1080},
            "colorDepth": 24,
            "pixelDepth": 24,
            "availableResolution": {"width": 1920, "height": 1032},
        },
        "viewport": {"width": 92, "height": 946},
        "tqdna": "102-3ba3e85cf7961244f473eb19390ded7fce52e443ae642873b84259744e1184472f259bdb689EAA555453202572a7e250",
        "t": 1755231032352,
    }


# 使用示例
def main():
    # 创建加密器实例
    encryptor = TrailEncryptor()

    print("=== 轨迹数据加密测试 ===")

    # 使用你提供的轨迹数据
    trail_data = {
        "trail": [
            {"x": 110, "y": 6, "t": 1755228768034, "s": 1.281, "tm": 86, "isd": 0},
            {"x": 110, "y": 6, "t": 1755228768034, "s": 0, "tm": 0, "isd": 0},
            {"x": 155, "y": 24, "t": 1755228768041, "s": 6.9238, "tm": 7, "isd": 0},
            {"x": 421, "y": 547, "t": 1755228770817, "s": 0.0017, "tm": 577, "isd": 0},
        ],
        "click": [{"x": 421, "y": 547, "t": 1755229520643}],
        "hover": [],
        "slider": [],
        "startTime": 1755228767948,
        "endTime": 1755231032352,
        "browser": {"name": "Edge", "version": "139.0.0.0"},
        "tqdna": "102-3ba3e85cf7961244f473eb19390ded7fce52e443ae642873b84259744e1184472f259bdb689EAA555453202572a7e250",
        "t": 1755231032352,
    }

    # 加密轨迹数据
    result = encryptor.encrypt_trail_data(trail_data)

    if result:
        print(f"✓ 轨迹数据加密成功")
        print(f"  原始数据大小: {result['original_size']} 字节")
        print(f"  加密后大小: {result['encrypted_size']} 字节")
        print(f"  压缩比: {result['compression_ratio']:.2f}")
        print(f"  加密结果: {result['encrypted'][:100]}...")  # 只显示前100个字符
        print(f"  时间戳: {result['timestamp']}")
    else:
        print("✗ 轨迹数据加密失败")

    print("\n" + "=" * 50)

    # 测试单个坐标加密（向后兼容）
    print("=== 单坐标加密测试 ===")
    coord_result = encryptor.encrypt_coordinates(421, 547)
    if coord_result:
        print(f"坐标 (421, 547) 加密结果: {coord_result['encrypted']}")


if __name__ == "__main__":
    main()
